package com.hh.subClass.service.impl;/*
 * @Auther:ZhengXueCheng
 * @Date:2023/7/24
 * @VERSON:1.8
 */

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hh.commen.PageVO;
import com.hh.subClass.vo.*;
import com.hh.subClass.bean.SpareChild;
import com.hh.subClass.mapper.SpareChildMapper;
import com.hh.subClass.service.SubClassService;
import com.hh.utils.FileCheck;
import com.hh.utils.ResultVo;
import org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class SubClassServiceImpl implements SubClassService {
    @Autowired
    private SpareChildMapper spareChildMapper;
    @Override
    public ResultVo addSubClass(AddSubClassVo addSubClassVo) {
        if (spareChildMapper.judgeCodeExist(addSubClassVo.getCode()) != null) {
            return ResultVo.error("备件小类编码重复");
        }
        if (spareChildMapper.judgeNameExist(addSubClassVo.getName()) != null) {
            return ResultVo.error("备件小类名称重复");
        }
        SpareChild spareChild = new SpareChild();
        if (addSubClassVo.getStatus()) {
            spareChild.setStatus(1);
        } else {
            spareChild.setStatus(0);
        }
        spareChild.setSpareCode(addSubClassVo.getCode());
        spareChild.setSpareName(addSubClassVo.getName());
        spareChild.setDescription(addSubClassVo.getRemark());
        Date date = new Date();
        spareChild.setCreateTime(date);
        spareChild.setUpdateTime(date);

        int row = spareChildMapper.insert(spareChild);
        if(row == 0){
            return ResultVo.error("添加失败");
        }
        return ResultVo.success();
    }

    @Override
    public PageVO findAllByPage(SubClassVo subClassVo) {
        PageHelper.startPage(subClassVo.getPageIndex(), subClassVo.getPageSize());
        List<SpareChild> spareChildList = spareChildMapper.selectAllByPage(subClassVo);
        PageInfo<SpareChild> pageInfo = new PageInfo<>(spareChildList);
        PageVO pageVO = new PageVO();
        pageVO.setData(pageInfo.getList());
        pageVO.setTotalNumber(pageInfo.getTotal());
        pageVO.setTotalPage(pageInfo.getPageNum());
        return pageVO;
    }

    @Override
    public Boolean updateStatus(StatusChangeVo statusChangeVo) {

        int row = spareChildMapper.updateStatusByPrimaryKey(statusChangeVo.getId(),statusChangeVo.getStatus());
        if (row == 1) {
            return true;
        }
        return false;
    }

    @Override
    public ResultVo updateSubClass(UpdateSubClassVo updateSubClassVo) {
        if(spareChildMapper.judgeUpdateStatus(updateSubClassVo.getId(),updateSubClassVo.getStatus()) == 1){
            return ResultVo.error("当前状态为启用");
        }
        if (spareChildMapper.judgeUpdateName(updateSubClassVo.getId(), updateSubClassVo.getName()) != null ) {
            return ResultVo.error("备件小类名称重复");
        }
        SpareChild spareChild = new SpareChild();
        spareChild.setId(updateSubClassVo.getId());
        spareChild.setSpareName(updateSubClassVo.getName());
        spareChild.setStatus(updateSubClassVo.getStatus());
        spareChild.setDescription(updateSubClassVo.getRemark());
        Date date = new Date();
        spareChild.setUpdatePerson(null);
        spareChild.setUpdateTime(date);
        spareChild.setVersion(updateSubClassVo.getVersion());

        int row = spareChildMapper.updateByPrimaryKey(spareChild);
        if (row == 1) {
            return ResultVo.success();
        }
        return ResultVo.error("更新失败");
    }

    @Override
    public ResultVo getAllSubClassList() {
        return ResultVo.success(spareChildMapper.selectAllAsList());
    }

    @Override
    public ResultVo importFile(MultipartFile file) throws IOException {
        //判断如果用户直接改的文件后缀名称进行提交      eg:excel.xls 直接改为excel.xlsx进行提交
        try {
            //1.判断是否空文件
            if (file.isEmpty()){
                return ResultVo.error("您选择了一个空文件,请重新选择！");
            }

        String fileName = file.getOriginalFilename();
        //2.做格式校验
        if (!FileCheck.checkFileEndForExcel2007(fileName)){
            return ResultVo.error("您所选择的Excel类型错误，请选择结尾为.xlsx的文件！");
        }
        //使用poi读取内容
        XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
        //获取单元格中的信息 at0是获取sheet1中的数据。
        XSSFSheet sheet = workbook.getSheetAt(0);
        String stringCellValue = sheet.getRow(0).getCell(0).getStringCellValue();
        if (!stringCellValue.equals("备件小类导入模板")){
            return ResultVo.error("导入模板不正确，请重新选择模板！");
        }
        //用两个list来判断是否重复录入
        List<String> nameList = new ArrayList<>();
        List<String> codeList = new ArrayList<>();
        Integer status = 0;
        //读取里面的内容放到list<对象>
        List<SubClassImport> subClassVoList = new ArrayList<>();
        for(int i = 4;i<=sheet.getLastRowNum();i++){
            //设置Excel在获取数据时就直接进行校验，如果这一行是空数据，就跳过，不做录入，获取下一行的数据
            String code = sheet.getRow(i).getCell(1).getStringCellValue();
            //检查不能为空
            if (code.isEmpty()){
                return ResultVo.error("您录入的第"+(i+1)+"行编码不能为空!");
            }
            //检查编码是否超长度
            if (code.length()>20){
                return ResultVo.error("您录入的di"+(i+1)+"行编码"+code+"过长,请减少输入字符");
            }
            //检查录入是否重复
            if (codeList.contains(code)){
                return ResultVo.error("您录入的第"+(i+1)+"行编码"+code+"录入重复，请重新录入!");
            }
            String name = sheet.getRow(i).getCell(2).getStringCellValue();
            //检查名称是否为空
            if (name.isEmpty()){
                return ResultVo.error("您录入的第"+(i+1)+"行编码"+code+"的名称不能为空！");
            }
            //检查是否超长
            if (name.length()>20){
                return ResultVo.error("您所录入的第"+(i+1)+"行编码"+code+"的名称"+name+"过于长，请减少字符数！");
            }
            //检查录入是否重复
            if (nameList.contains(name)){
                return ResultVo.error("您录入的第"+(i+1)+"行编码"+code+"的名称"+name+"录入重复，请重新录入!");
            }
            String remark = sheet.getRow(i).getCell(3).getStringCellValue();
            //检查是否超长
            if (remark.length()>50){
                return ResultVo.error("您所录入的第"+(i+1)+"行编码"+code+"的描述过于长，请重新录入！");
            }
            String statusName = sheet.getRow(i).getCell(4).getStringCellValue();
            //进行状态转换(如果禁用或不填的情况下，默认禁用)
            if (statusName.equals("启用")){
                status = 1;
            }else {
                status = 0;
            }
            SubClassImport subClassVo = new SubClassImport(code,name,remark,statusName,status);
            subClassVoList.add(subClassVo);
            nameList.add(name);
            codeList.add(code);
        }
        //获取原有的备件小类的信息
        List<SubClassImport> dataList =spareChildMapper.getAllSubclass();
        //进行查重
        for (int i = 0; i < subClassVoList.size()-1; i++) {
            for (int j = 0; j < dataList.size()-1; j++) {
                //如果code出现重复
                if (subClassVoList.get(i).getCode().equals(dataList.get(j).getCode())){
                    return ResultVo.error("您所录入的第"+(i+1)+"个编码已经存在，请重新录入！");
                }
                //如果name重复
                if (subClassVoList.get(i).getName().equals(dataList.get(j).getName())){
                    return ResultVo.error("您所录入的第"+(i+1)+"个名称已经存在，请重新录入！");
                }
            }
        }
        //执行批量插入
        spareChildMapper.insertFromFile(subClassVoList);
        return ResultVo.success("所有数据均已成功录入！");
        }catch (OLE2NotOfficeXmlFileException e){
            e.printStackTrace();
            return ResultVo.error("请您核实该Excel文件是否被改过后缀格式！请重新选择xlsx文件！");
        }
    }

}
